

Ember.EntityRoute = Ember.Route.extend({
	beforeModel : function(){
		this.store = new Store(this);
	},
	setupController : function(controller, model){
		controller.store = this.store;
		controller.set('model', model);
		// Ember.Route.call(this).setupController(controller, model);
	},
	model : function (params){
    // console.log('params', params, this.store);
    // console.log('route.namte', this.routeName)
    if(params.id){
    	return this.store.find(params.id);
    }
		return this.store.find({pageIndex:params.pageIndex, 
			pageSize: params.pageSize, route: this});
	}
});
Ember.PageRoute = Ember.EntityRoute.extend({
	setupController: function(controller, model) {
		var data = this.data;
		controller.set('pageIndex', data.pageIndex);
		controller.set('pageSize', data.pageSize);
    controller.set('totalItems', data.totalItems);
		controller.set('model', model);
	}
});

Ember.PageController = Ember.Controller.extend({
	
});

Ember.PageController = Ember.Controller.extend({
	pageLast: function(){
		return Math.ceil(this.totalItems * 1.0 / this.pageSize);
	}.property('pageSize', 'totalItems'),
	isPageFirst: function(){
		return this.pageIndex == 1;
	}.property('pageIndex'),
	pagePrev: function(){
		return this.pageIndex == 1 ? 1 : this.pageIndex - 1;
	}.property('pageIndex'),
	pageNext: function(){
		return this.get('pageLast') == this.pageIndex ? this.pageIndex : this.pageIndex + 1;
	}.property('pageIndex'),
	isPageLast: function(){
		// console.log('isPageLast',this.get('pageLast'), this.pageIndex)
		return this.get('pageLast') == this.pageIndex;
	}.property('pageLast', 'pageIndex'),
	pageIndexs : function(){
		var list = [];
		var start = 1, end = this.get('pageLast');
		var index = this.pageIndex;
		list.push(start);
		for(var i = start + 1; i < end; i++){
			if(Math.abs(i - index) <= 2){
				list.push(i);
			}
		}
		list.push(end);
		// console.log(list)
		return list;
	}.property('pageIndex','pageSize','totalItems')
});

function Store(route){
	// var name = route.entityName;
	var host = 'http://192.168.103.24:8080/code-ds/';
	this.find = function(a, b){
		var name = route.entityName;
		if(typeof(a) != 'object'){
			return this.findById(a, b);
		}
		var opts = a;
		var url = host + name + '.json?pageSize=' + 
			opts.pageSize + '&pageIndex=' + opts.pageIndex;	
		return Ember.$.getJSON(url).then(function(data){
			route.data =  data;
			return data.items;
		});
	}
	// return Ember.$.getJSON("http://192.168.103.24:8080/code-ds/person/nations/"+params.nation_id+".json");
	this.findById = function(id, opts){
		var name = route.entityName;
		var url = host + name + '/' + id + '.json';
		return Ember.$.getJSON(url);
	}

	this.save = function(model){
		var name = route.entityName;
		var url = host + name;
		if(model.id){
			url += '/' + model.id
		}
		url += '?_method=PUT'
		return Ember.$.post(url, {'data': JSON.stringify(model)});
	}
};